package cn.sunxiansheng.consumer.error;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Description: 处理失败消息的交换机和队列
 *
 * @Author sun
 * @Create 2024/12/31 19:07
 * @Version 1.0
 */
@Configuration
// 当配置文件中spring.rabbitmq.listener.simple.retry.enabled=true时，才会生效
@ConditionalOnProperty(prefix = "spring.rabbitmq.listener.simple", name = "retry.enabled", havingValue = "true")
public class ErrorConfiguration {

    /**
     * 一个error交换机
     */
    @Bean
    public DirectExchange errorExchange() {
        return new DirectExchange("error.exchange");
    }

    /**
     * 一个error队列
     */
    @Bean
    public Queue errorQueue() {
        return new Queue("error.queue");
    }

    /**
     * 绑定error队列到error交换机
     */
    @Bean
    public Binding errorBinding() {
        return BindingBuilder.bind(errorQueue()).to(errorExchange()).with("error");
    }

    /**
     * MessageRecoverer
     */
    @Bean
    public MessageRecoverer myMessageRecoverer(RabbitTemplate rabbitTemplate) {
        // 指定错误消息发送到error.exchange交换机，routingKey为error
        return new RepublishMessageRecoverer(rabbitTemplate, "error.exchange", "error");
    }
}